package auction.serveroutage;


import java.io.*;
import java.net.*;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import auction.client.Client;

public class ClientTimeStampServer extends Thread  {
	public static Logger log = Logger.getLogger(ClientTimeStampServer.class);

	private ExecutorService executor = Executors.newCachedThreadPool();

	private  ServerSocket s;

	private boolean resume = true;

	public ClientTimeStampServer(int tcpport){
		try {		

			s = new ServerSocket(tcpport);
			log.debug("ClientTimeStampServer socket has been established");


		} 
		catch (IOException e) {
			
			System.out.println("Could not bind to port " + tcpport + " - "
					+ e.getMessage());
			resume = false;
			Client.cleanUp(0);
			Client.setEnded(true);
			
		}


	}
	@Override
	public void run() {
		log.debug("ClientTimeStampServer has been started");
		try {
			while (resume){
				Socket tempsoc;
				//Accept eingehende Verbindung
				tempsoc = s.accept();
				//Uebergebe Verbindungsdaten an neue Session
				TimeStampSession newSession = new TimeStampSession(tempsoc);

				//Verwende fuer neue Session einen Thread aus Threadpool
				executor.execute(newSession);
			}
		} catch (IOException e) {
			log.debug("Server successfully shut down!");
		}		
	}
	
	public void shutdown(){
		try{


			//Shudown Threadpool
			executor.shutdown();


			try{
				s.close();
			}
			catch (SocketException e){
				log.debug("Error: Socket closing");
			} catch (IOException e) {
				log.debug("Error: Socket closing");
			}

		}

		catch(NoSuchElementException e){
			log.debug(e.getMessage());
		}
	}


	public boolean isResume() {
		return resume;
	}
	public void setResume(boolean resume) {
		this.resume = resume;
	}



}

